package com.sanyue.oj.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sanyue.oj.common.ErrorCode;
import com.sanyue.oj.constant.CommonConstant;
import com.sanyue.oj.exception.BusinessException;
import com.sanyue.oj.mapper.QuestionSubmitMapper;
import com.sanyue.oj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.sanyue.oj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.sanyue.oj.model.entity.*;
import com.sanyue.oj.model.entity.QuestionSubmit;
import com.sanyue.oj.model.enums.CodeLanguageEnum;
import com.sanyue.oj.model.enums.QuestionSubmitStatusEnum;
import com.sanyue.oj.model.vo.QuestionSubmitVO;
import com.sanyue.oj.model.vo.QuestionSubmitVO;
import com.sanyue.oj.service.QuestionService;
import com.sanyue.oj.service.QuestionSubmitService;
import com.sanyue.oj.service.UserService;
import com.sanyue.oj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author admin
* @description 针对表【question_submit(题目提交)】的数据库操作Service实现
* @createDate 2025-03-04 20:10:50
*/
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {


    @Resource
    private QuestionService questionService;
    
    @Resource
    private UserService userService;


    /**
     * 用户提交答案
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        //检验编程语言是否合法
        String language = questionSubmitAddRequest.getLanguage();
        if (CodeLanguageEnum.getEnumByValue(language) == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"编程语言不存在");
        }
        //判断用户是否输出答案
        String code = questionSubmitAddRequest.getCode();
        if(StringUtils.isAnyBlank(code)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"提交答案为空");
        }
        //判断题目是否存在
        Long questionId = questionSubmitAddRequest.getQuestionId();
        if (questionId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"未查询到该题目");
        }
        if (questionService.getById(questionId) == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"未查询到该题目");
        }

        QuestionSubmit questionSubmit = BeanUtil.copyProperties(questionSubmitAddRequest, QuestionSubmit.class);
        //设置题目初始状态：注意全部设置，不要忘了直接 allSet
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setUserId(loginUser.getId());
        questionSubmit.setJudgeInfo("{}");
        boolean save = this.save(questionSubmit);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据插入失败");
        }
        return questionSubmit.getId();
    }

    /**
     * 分页获取用户提交答案类封装
     *
     * @param questionSubmitPage
     * @param request
     * @return
     */
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, HttpServletRequest request) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionSubmitList.stream().map(QuestionSubmit::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit -> {
            QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
            Long userId = questionSubmit.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionSubmitVO.setUserVO(userService.getUserVO(user));
            return questionSubmitVO;
        }).collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

    /**
     * 获取查询条件
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        Long id = questionSubmitQueryRequest.getId();
        String language = questionSubmitQueryRequest.getLanguage();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        
        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


}




